﻿/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Shared/Base/Thread_WIN32.h"
#include "Shared/Global_Macros.h"
#include "Shared/Base/Runnable.h"

namespace Shared {

    ThreadImpl::ThreadImpl(Runnable *runnable)
        : _id(0)
        , _handle(-1L)

        , _runnable(runnable)
    {

    }

    ThreadImpl::~ThreadImpl(void)
    {
        if (_handle != -1L) {
            CloseHandle((HANDLE)_handle);
        }
    }

    bool ThreadImpl::startImpl(void)
    {
        SHARED_ASSERT(_handle == -1L);
        _handle = ::_beginthreadex(NULL, 0, ThreadImpl::proc,
            this, 0, (unsigned int*)&_id);
        return _handle != -1L;
    }

    void ThreadImpl::joinImpl(void)
    {
        SHARED_ASSERT(_handle != -1L);
        if (_handle != -1L) {
            WaitForSingleObject(HANDLE(_handle), INFINITE);
        }
    }

    bool ThreadImpl::joinableImpl(void)
    {
        return _handle != -1L;
    }

    bool ThreadImpl::setPriorityImpl(int priority)
    {
        return SetThreadPriority((HANDLE)_handle, priority) != FALSE;
    }

	ThreadImpl::ID ThreadImpl::currentThreadIdImpl(void)
	{
		return GetCurrentThreadId();
	}

	void ThreadImpl::sleepImpl(long miliseconds)
	{
		::Sleep((DWORD)miliseconds);
	}

    unsigned int ThreadImpl::proc(void* arg)
    {
        SHARED_ASSERT(arg != NULL);
        ThreadImpl* pth = static_cast<ThreadImpl*>(arg);
        pth->_runnable->run();
        return 0;
    }

}